from pluginsCategories import pySKFWDaemons
import os,time
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import simplejson as json
import logging
debugMode = False

class pySKFWHttpdServer(pySKFWDaemons):
    name = 'pySKFWHttpdServer'
    def init(self,psrv):
        self.port = 8888
        logging.info("serving httpRoot at port %s" % (self.port))
        self.URLS=[]    
    def start(self,server):
        root = os.path.join(os.path.dirname(__file__), "../httpRoot")
        self.URLS.append((r"/"     ,MainHandler, {"root": root+"/index.html"}))
        self.URLS.append((r"/(.*)" ,tornado.web.StaticFileHandler, {"path": root}))
        self.application = tornado.web.Application(self.URLS)
        self.http_server = tornado.httpserver.HTTPServer(self.application)
        self.http_server.listen(self.port)
        tornado.ioloop.IOLoop.instance().start()        
        
    def addReturnHandler(self,resultType,path,handler):
        self.URLS.append((path , pySKFWHttpdHandler,{'server':self,'resultType':resultType,'handler':handler}))
        
    def stop(self):
        self.http_server.stop()
        
class MainHandler(tornado.web.RequestHandler):
    def initialize(self,root):
        self.root= root
    def get(self):
        raw_file=open(self.root)
        self.write(raw_file.read())

class pySKFWHttpdHandler(tornado.web.RequestHandler):
    def initialize(self,server,resultType,handler):
        self.server = server
        self.resultType = resultType
        self.handler = handler
    def get(self,*prm):
        if (self.resultType == 'img'):
            self.set_header("Content-Type","image/jpeg")
            tmp = self.handler(*prm)
            if (tmp):
                self.write(tmp)
        if (self.resultType == 'lst'):
            self.set_header('Content-Type','text/plain')
            self.write(json.dumps(self.handler(*prm)))
        if (self.resultType == 'txt'):
            self.set_header('Content-Type','text/html')
            self.write(self.handler(*prm))
        if (self.resultType == 'bnr'):
            self.set_header('Content-Type','text/jpeg')
            self.write(self.handler(*prm))
        return
    
